package net.comic.entities

import java.math.*
import org.codehaus.groovy.grails.commons.GrailsResourceUtils

class Comic {
	def grailsApplication
	
	//	Persistence Attributes
	String 	name
	String 	description
	Author	author
	String 	imagePath
	boolean rateable = true
	boolean disabled = false
	
	Date 	dateCreated
	Date 	lastUpdated

	
	//	Not Persistence Attributes
	static 	transients = ['rate', 'absoluteImagePath']	
	

	
	//	DB Relations
 	static 	belongsTo = [createdBy:	User]
 	
	static 	hasMany = 	[page:		Page,
	                 	 comments:	Comment,
	                 	 ratings:	Rate,
	                 	 tags:		Tag]

	//	DB Constraits
	static constraints = {
		name(blank:false, unique:true, maxSize:50)
		description(nullable:true, maxSize:1000)
		author(nullable:true)
		imagePath(nullable:true, blank:true)
	}

	
	//	Default order to sort
	static mapping = { sort "name" }

	
	//	Other Methods
	String getRate() {
		//	Calculem la mitja de les puntuacions rebudes fins ara
		Float p = 0
		if(ratings){
			ratings.each(){ p += it.rate }
			p = p / ratings.size()
		}
		return p
	}
	
	
	String getAbsoluteImagePath() {
		return grailsApplication.config.comics.uploadAbsoluteComicPath + imagePath
	}
	
	String getAbsoluteImagePath(file) {
		return grailsApplication.config.comics.uploadAbsoluteComicPath + file + "/"
	}
}